<template>
	<div  v-show="visible">
		<van-field readonly clickable :label="componentModel.label" v-model="vue_model_label" @click="showPicker()" />
		<van-popup v-model:show="showPicker_model" position="bottom">
			<van-datetime-picker v-model="vue_model" type="datetime" @cancel="closePicker()" @confirm="onConfirm"/>
		</van-popup>
	</div>
</template>

<script>
	import {
		sendComponentValueChangeRequest
	} from '@/utils/requestUtils.js';
	import utils from '@/utils/utils.js';
	export default {
		name: "DatetimeComponent",
		props: ["componentModel", "scope"],
		data() {
			return {
				vue_model: "",
				vue_model_label: "",
				showPicker_model: false,
				visible:true,
				readonly:false,
				label:"",
			}
		},
		inject:['children'],
		mounted() {
			this.children.push(this);
		},beforeUnmount() {
			utils.removeArrayElement(this.children,this);
		},
		methods: {
			onConfirm(value) {
				var sMonth=value.getMonth()+1+"";
				if(value.getMonth()+1<10){
					sMonth="0"+(value.getMonth()+1);
				}
				var sDate=value.getDate()+"";
				if(value.getDate()+1<10){
					sDate="0"+value.getDate();
				}
				var sHours=value.getHours();
				if(value.getHours()<10){
					sHours="0"+value.getHours();
				}
				var sMinutes=value.getMinutes();
				if(value.getMinutes()<10){
					sMinutes="0"+value.getMinutes();
				}
				var sSeconds=value.getSeconds();
				if(value.getSeconds()<10){
					sSeconds="0"+value.getSeconds();
				}
				this.vue_model_label =value.getFullYear()+"-"+sMonth+"-"+sDate+
				" "+sHours+":"+sMinutes+":"+sSeconds;
				this.showPicker_model = false;
				this.onValueChangeHandler();
			},
			onValueChangeHandler() {
				if (this.scope != undefined) {
					this.$emit("onValueChange", this);
					return;
				}
				sendComponentValueChangeRequest(this);
			},
			getValue() {
				return this.vue_model_label;
			},
			setProp(prop) {
				for (var k in prop) {
					if (k == "value") {
						if (prop[k] == null) {
							this.vue_model = new Date();
							this.vue_model_label="";
						} else {
							var dateTimeArray=prop[k].split(" ");
							var dateArray=dateTimeArray[0].split("-");
							var timeArray=dateTimeArray[1].split(":");
							this.vue_model = new Date(dateArray[0],dateArray[1]-1,dateArray[2],
							timeArray[0],timeArray[1],timeArray[2]);
							this.vue_model_label=prop[k];
						}
					}else if (k == "visible") {
							this.visible = prop[k];
						} else if (k == "readonly") {
							this.readonly = prop[k];
						}else if(k=="label"){
						this.label=prop[k];
					}
				}
			},
			showPicker() {
				if (this.readonly) {
					return;
				}
				this.showPicker_model = true;
			},
			closePicker() {
				this.showPicker_model = false
			}
		}
	}
</script>

<style>
</style>
